$(function() {

	$( ".columns" ).sortable({
		  handle: '.box-title',
	      connectWith: ".columns",
	      //placeholder: "ui-widget-state-highlight",
	      update: function( event, ui ) {
	    	  if(ui.sender == null) {
	    		  return;
	    	  }
        	  var index = 1;
        	  var $parent = ui.item.parent();
        	  var columnid = $parent.data('column');
        	  var rowid = ui.item.index();
        	  var wid = ui.item.data('widget-id');
        	  // Reorder the table
        	  $.ajax({
    			  type: "POST",
    			  url: "?mod=dashboard&act=api&xvtrs=none",
    			  dataType:"json",
    			  contentType:"application/json; charset=utf-8",
    			  data: '{"id":"'+wid+'","position":"'+columnid+','+rowid+'"}'
    		}).done(function( msg ) {
    			$.fn.foxmessage(msg);
    		});
          }
	    }).disableSelection();

	// Add On click event to Widgets
	$('a.act-reload').click(function() {
		var id = $(this).data('widget-id');
		var $container = $('#'+id+'_frame');	
		if($container.data('mode') == 'ajax') {
			$.ajax({
				  type: "POST",
				  url: $container.data('uri')
			}).done(function( data ) {
				$container.parent().get(0).innerHtml = data;
			});
		} else {
			document.getElementById(id).contentDocument.location.reload(true);
		}
		return false;
	});
	// Add Open/Close Widgets
	$('a.act-off').click(function() {
		var id = $(this).data('container-id');
		var wid = $(this).data('widget-id');
		var $container = $(jq(id));
		if($container.is(':visible')) {
			$container.hide();
			var visible = false;
		} else {
			$container.show();
			var visible = true;
		}
		$.ajax({
			  type: "POST",
			  url: "?mod=dashboard&act=api&xvtrs=none",
			  dataType:"json",
			  contentType:"application/json; charset=utf-8",
			  data: '{"id":"'+wid+'","attribute":"visibility","visibility":'+visible+'}'
		}).done(function( msg ) {
			$.fn.foxmessage(msg);
		});
		return false;
	});
	// Action Remove Widget from dashboard
	$('a.act-remove').click(function() {
		var id = $(this).data('container-id');
		var wid = $(this).data('widget-id');
		var $container = $(jq(id));
		$container.html('').remove();
		// Sent deletion to the server
		$.ajax({
			  type: "POST",
			  url: "?mod=dashboard&act=api&xvtrs=none",
			  dataType:"json",
			  contentType:"application/json; charset=utf-8",
			  data: '{"id":"'+wid+'","attribute":"remove","remove":true}'
		}).done(function( msg ) {
			$.fn.foxmessage(msg);
		});
		return false;
	});
});